#include "specialsproxymodel.h"


#include <dtwentymodel.h>


SpecialsProxyModel::SpecialsProxyModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
    m_level = 0;
}

QVariant SpecialsProxyModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::CheckStateRole)
    {
        return QSortFilterProxyModel::data(index, role);
    }

    if (m_classLevels.isNull())
    {
        return QVariant();
    }

    QList<ClassLevel*> levels = m_classLevels->findChildren<ClassLevel*>(QString(), Qt::FindDirectChildrenOnly);
    ClassLevel* level = levels.value(m_level, 0);
    if (!level)
    {
        return QVariant();
    }

    foreach (SpecialAbility* special, level->findChildren<SpecialAbility*>(QString(), Qt::FindDirectChildrenOnly))
    {
        if (special->name() == index.data().toString())
        {
            return Qt::Checked;
        }
    }

    return Qt::Unchecked;

}

bool SpecialsProxyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (role != Qt::CheckStateRole)
    {
        return QSortFilterProxyModel::setData(index, value, role);
    }


    if (m_classLevels.isNull())
    {
        return false;
    }

    QList<ClassLevel*> levels = m_classLevels->findChildren<ClassLevel*>(QString(), Qt::FindDirectChildrenOnly);
    ClassLevel* level = levels.value(m_level, 0);
    if (!level)
    {
        return false;
    }

    foreach (SpecialAbility* special, level->findChildren<SpecialAbility*>(QString(), Qt::FindDirectChildrenOnly))
    {
        // class skill exists
        if (special->name() == index.data().toString())
        {
            if (value.toInt() == Qt::Checked)
            {
                return false;
            }

            special->setParent(0);
            special->deleteLater();

            emit dataChanged(index, index);
            return true;
        }
    }

    if (value.toInt() == Qt::Unchecked)
    {
        return false;
    }

    SpecialAbility* special = qobject_cast<SpecialAbility*>(level->newChild());
    special->setReferencePath(index.data(DTwentyModel::Role_PATH).toString());

    emit dataChanged(index, index);
    return true;
}

Qt::ItemFlags SpecialsProxyModel::flags(const QModelIndex &index) const
{
    return QSortFilterProxyModel::flags(index) | Qt::ItemIsUserCheckable;
}

void SpecialsProxyModel::setClassLevels(const QModelIndex &sourceIndex)
{
    m_classLevels = reinterpret_cast<ClassLevels*>(sourceIndex.internalPointer());
}

void SpecialsProxyModel::setClassLevel(int level)
{
    m_level = level;
}


